package com.example.wan_android.viewmodel

import android.content.Intent
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.wan_android.http.bean.KnowledgeBodyBeansData
import com.example.wan_android.http.code.KnowledgeBodyRepository
import com.example.wan_android.ui.activity.WebActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class KnowledgeBodyViewModel : BaseViewModel() {
    companion object {
        const val id = "id"
        const val index = "index"
        const val title = "title"
    }

    private val _knowledgeBodyData = MutableLiveData<Result<List<KnowledgeBodyBeansData>>>()
    val knowledgeBodyData = _knowledgeBodyData
    var mId: Int = 0
    var mIndex: Int = 0
    var mTitle: String = ""
    private val _isSuccess = MutableLiveData<Boolean>(false)
    val isSuccess = _isSuccess


    fun getKnowledgeBodyData() {
        _isSuccess.value = false
        viewModelScope.launch {
            // 使用局部变量避免污染成员变量
            var currentIndex = mIndex
            // 创建临时可变集合
            val accumulatedList = mutableListOf<KnowledgeBodyBeansData>()

            try {
                do {
                    // 带线程调度的网络请求
                    val result = withContext(Dispatchers.IO) {
                        KnowledgeBodyRepository().fetchKnowledgeBody(currentIndex, mId)
                    }

                    // 成功时处理数据
                    if (result.isSuccess) {
                        result.getOrNull()?.let { data ->
                            if (data.isNotEmpty()) {
                                accumulatedList.addAll(data)
                                currentIndex++  // 索引自增准备下次请求
                            } else {
                                return@let  // 数据为空时退出循环
                            }
                        }
                    } else {
                        // 失败时传递错误
                        _knowledgeBodyData.postValue(result)
                        return@launch
                    }
                } while (result.getOrNull()?.isNotEmpty() == true)

                // 最终传递合并结果
                _knowledgeBodyData.postValue(Result.success(accumulatedList))

            } catch (e: Exception) {
                // 异常处理
                _knowledgeBodyData.postValue(Result.failure(e))
            } finally {
                _isSuccess.value = true
            }
        }
    }

    fun openWeb(url: String) {
        startActivity(Intent().apply {
            putExtra(WebViewModel.url, url)
        }, targetClass = WebActivity::class.java)
    }
}